package com.vm.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.vm.model.ActiveSoft;
import com.vm.utils.ApkUtils;
import com.vm.utils.JsonUtils;
import com.vm.utils.MyDisplayImageOptions;
import com.vm.utils.MyTimerTask;
import com.vm.utils.MyVolley;
import com.vm.commons.CurrentUser;
import com.vm.commons.StringUtil;
import com.vm.commons.VMConst;
import com.wwtscapp.apk.R;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 * @ProjectName: [WeiMai]
 * @Author: [kent.wang]
 * @CreateDate: [2015年3月16日 下午3:28:11]
 * @Version: [v1.0]
 * 
 */
public class ShakeActivity extends Activity implements SensorEventListener {
	protected static final String TAG = null;
	SensorManager sensorManager = null;
	Vibrator vibrator = null;
	private List<ActiveSoft> listsoft;
	private RequestQueue mQueue;
	private ImageView iv_userImage;
	private TextView tv_userName;
	private LinearLayout f_item_ll;
	ImageView imgbtn_search_back;
	private String softId;
	private static boolean isReady = true;
	TextView tv_chance_number;
	boolean addRecord = false;
	ActiveSoft activeSoft;
	boolean isInstalled;
	int countDown = 5;
	Timer timer;
	private MyTimerTask mTimerTask;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wave);
		mQueue = MyVolley.getRequestQueue();
		init();
		updateNum();
		sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
		vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);
		listsoft = new ArrayList<ActiveSoft>();
		// iv_waveImage.setOnClickListener(imgClickListener);
		String url = VMConst.REQUEST_URL + "getByActiveType?typeId=" + 19;
		JsonArrayRequest jsonObjectRequest = new JsonArrayRequest(url,
				new Listener<JSONArray>() {

					@Override
					public void onResponse(JSONArray arg0) {
						// TODO Auto-generated method stub
						for (int i = 0; i < arg0.length(); i++) {
							try {
								JSONObject jsonObject = arg0.getJSONObject(i);
								// String s=jsonObject.toString();

								ActiveSoft activesoft = JsonUtils.jsonToBean(
										jsonObject, ActiveSoft.class);
								if (activesoft != null) {
									listsoft.add(activesoft);
								}
							} catch (JSONException e) {
								e.printStackTrace();
							}
						}

					}

				}, new Response.ErrorListener() {
					public void onErrorResponse(VolleyError error) {
						Log.e(TAG, error.getMessage(), error);
					}
				});
		mQueue.add(jsonObjectRequest);

	}

	protected void onPause() {
		super.onPause();
		sensorManager.unregisterListener(this);
	}

	@Override
	protected void onResume() {
		super.onResume();
		sensorManager.registerListener(this,
				sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
				SensorManager.SENSOR_DELAY_NORMAL);
	}

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {
		// 当传感器精度改变时回调该方法，Do nothing.
	}

	@Override
	public void onSensorChanged(SensorEvent event) {
		addRecord = false;

		// TODO Auto-generated method stub
		int sensorType = event.sensor.getType();
		// values[0]:X轴，values[1]：Y轴，values[2]：Z轴
		float[] values = event.values;
		if (sensorType == Sensor.TYPE_ACCELEROMETER) {
			if (isReady) {
				if ((Math.abs(values[0]) > 19 || Math.abs(values[1]) > 19 || Math
						.abs(values[2]) > 19)) {
					timer = new Timer(true);
					mTimerTask = new MyTimerTask(countDown, handler);
					timer.schedule(mTimerTask, 1000, 1000);
					isReady = false;
					Log.d("sensor x ", "============ values[0] = " + values[0]);
					Log.d("sensor y ", "============ values[1] = " + values[1]);
					Log.d("sensor z ", "============ values[2] = " + values[2]);
					f_item_ll.setVisibility(View.VISIBLE);
					do {
						activeSoft = listsoft
								.get((int) (Math.random() * listsoft.size()));
						isInstalled = ApkUtils.isAppInstalled(
								activeSoft.getPackageName(), this);
					} while (isInstalled);
					{

						com.nostra13.universalimageloader.core.ImageLoader
								.getInstance().displayImage(
										VMConst.URL + activeSoft.getImageUrl(),
										iv_userImage,
										MyDisplayImageOptions.getInstance());
						tv_userName.setText(activeSoft.getName());
						f_item_ll.setOnClickListener(ll_listener);
						softId = activeSoft.getSoftId();
						vibrator.vibrate(500);
						if (CurrentUser.USERID != null) {
							if (tv_chance_number.getText().toString()
									.equals("0")) {
								// 次数用尽
								Toast toast = Toast.makeText(
										ShakeActivity.this, "当天次数已用尽",
										Toast.LENGTH_SHORT);
								toast.show();
								addRecord = false;
							} else {
								String url = VMConst.REQUEST_URL
										+ "addShake?userId="
										+ CurrentUser.USERID + "&softId="
										+ softId;
								StringRequest stringRequest = new StringRequest(
										url, new Listener<String>() {

											@Override
											public void onResponse(String arg0) {
												// TODO Auto-generated method
												// stub
												if (arg0.equals("1")) {
													updateNum();
													addRecord = true;
												}
											}

										}, null);
								mQueue.add(stringRequest);
							}

						} else {
							// 未登录
							Toast toast = Toast.makeText(ShakeActivity.this,
									"未登录", Toast.LENGTH_SHORT);
							toast.show();
							addRecord = false;
						}
						isReady = true;
						isInstalled = true;
					}
				}
			}
		}

	}

	OnClickListener ll_listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(ShakeActivity.this, DetailActivity.class);
			intent.putExtra("softId", softId);
			if (addRecord = true) {
				intent.putExtra("addRecord", 1);
			}
			startActivity(intent);
		}
	};

	/**
	 * 初始化
	 */
	private void init() {
		tv_chance_number = (TextView) findViewById(R.id.tv_chance_number);
		iv_userImage = (ImageView) findViewById(R.id.iv_userImage);
		tv_userName = (TextView) findViewById(R.id.tv_userName);
		f_item_ll = (LinearLayout) findViewById(R.id.f_item_ll);
		// iv_waveImage = (ImageView) findViewById(R.id.iv_waveImage);
		imgbtn_search_back = (ImageView) findViewById(R.id.imgbtn_search_back);
		imgbtn_search_back.setOnClickListener(btn_backListener);
	}

	private void updateNum() {
		String url = VMConst.REQUEST_URL + "getShakeNum?date="
				+ StringUtil.getDate(4) + "&userId=" + CurrentUser.USERID;
		StringRequest stringRequest = new StringRequest(url,
				new Listener<String>() {

					@Override
					public void onResponse(String arg0) {
						// TODO Auto-generated method stub
						int number = 3 - Integer.parseInt(arg0);
						if (number < 0) {
							tv_chance_number.setText("0");
						} else {
							tv_chance_number.setText(Integer.toString(number));
						}
					}

				}, null);
		mQueue.add(stringRequest);
	}

	/**
	 * imgbtn_search_back 返回按钮监听
	 */
	OnClickListener btn_backListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			onBackPressed();
		}
	};

	/**
	 * 手机自带返回按钮监听
	 */
	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

	@SuppressLint("HandlerLeak")
	final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				String remainTime = msg.obj.toString();
				Log.d("remainTime", remainTime);
				isReady = false;
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				break;

			case 2:
				isReady = true;
				// task = null;
				// time
				timer.cancel();
				break;
			}

			super.handleMessage(msg);
		}
	};
}
